import 'package:flutter/material.dart';
import 'package:lx_widgets_library/lx_widgets_library.dart';

// 电池百分比自定义视图
class BatteryPercentView extends StatelessWidget {
  final double percent;
  final Color selectedColor;
  final Color normalColor;
  final Color textColor;
  final double width;
  final double height;
  final double space;
  final double radius;
  // 斜切角度
  final double skewXAlpha;
  final int count;

  BatteryPercentView({
    Key? key,
    required this.percent,
    Color? selectedColor,
    Color? normalColor,
    Color? textColor,
    this.width = 100,
    this.height = 20,
    this.radius = 4,
    this.skewXAlpha = -0.5,
    this.space = 2,
    this.count = 5,
  })  : textColor = LxWidgetsLibraryService.to.colorType.color6,
        selectedColor = LxWidgetsLibraryService.to.colorType.color6,
        normalColor =
            normalColor ?? LxWidgetsLibraryService.to.colorType.color6.withOpacity(0.3),
        assert(percent >= 0 && percent <= 1, 'Percent must be between 0 and 1'),
        assert(count > 0, 'Count must be greater than 0'),
        super(key: key);

  @override
  Widget build(BuildContext context) {
    int filledBlocks = (percent * count).round().clamp(0, count);
    return Row(
      mainAxisSize: MainAxisSize.min,
      children: [
        for (int i = 0; i < count; i++)
          Padding(
            padding: const EdgeInsets.symmetric(horizontal: 1.0),
            child: _buildBatteryBlock(i < filledBlocks),
          ),
        const SizedBox(width: 4),
        LxText(
          '${(percent * 100).toInt()}%',
          color: textColor,
          fontWeightEnum: LxFontWeightEnum.titleLarge,
        ),
      ],
    );
  }

  // 构建电池块
  Widget _buildBatteryBlock(bool isFilled) {
    double itemWidth = (width - (count - 1) * space) / count;
    double itemHeight = height;
    return Transform(
      transform: Matrix4.skewX(-0.5),
      child: Container(
        width: itemWidth,
        height: itemHeight,
        decoration: BoxDecoration(
          color: isFilled ? selectedColor : normalColor,
          borderRadius: BorderRadius.circular(radius),
        ),
      ),
    );
  }
}
